﻿using B.S.DataBase.MyProject.API.Appicant.Command;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Common___Jwt配置;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.UserCommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<User>>
    {
        private readonly IBaseRepository<User> userRepos;
        private readonly IConfiguration configuration;

        public LoginCommandHandler(IBaseRepository<User> userRepos,IConfiguration configuration)
        {
            this.userRepos = userRepos;
            this.configuration = configuration;
        }


        public Task<APIResult<User>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<User> result = new APIResult<User>();
            request.Password=GetMd5(request.Password);
            var login = userRepos.GetAll().Result.FirstOrDefault(x => x.UserName == request.UserName && x.Password == request.Password);
            if (login == null)
            {
                result.Code = APIEnum.登录失败密码或用户名错误;
                result.Msg = APIEnum.登录失败密码或用户名错误.ToString();
            }
            else
            {
                result.Code = APIEnum.登录成功;
                result.Msg = APIEnum.登录成功.ToString();
                var token = CreateTokenString(request.UserName,login.UserId);
                login.HamletName = token;
                result.data = login;
            }

            return Task.FromResult(result);

        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString(string UserName,int UserId)
        {
            var jwtSettings= configuration.GetSection("JwtSettings").Get<JwtSettings>();
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SigningKey);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //claims 指用户的信息， 用户名，用户ID，权限，角色ID
            var claims = new[]
            {
                new Claim("NickName",UserName),
                new Claim("UserId",UserId.ToString())
            };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,
                audience: jwtSettings.Audience,
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims:claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        private string GetMd5(string source)
        {
            var md5=MD5.Create();
            byte[] bytes=Encoding.UTF8.GetBytes(source);
            byte[] hash = md5.ComputeHash(bytes);
            string target =BitConverter.ToString(hash,0,hash.Length).Replace("-","");
            return target;
        }
    }
}
